const puppeteer = require('puppeteer')

const url = 'https://www.bilibili.com/ranking#!/all/0/0/30/'

const sleep = time => new Promise(resolve => {
  setTimeout(resolve, time)
})

;
(async () => {

  console.log('开始。。')

  const brower = await puppeteer.launch({
    args: ['--no-sandbox'],
    dumpio: false,
  })

  const page = await brower.newPage()

  await page.goto(url, {
    waitUntil: 'networkidle2'
  })

  await autoScroll(page)

  const result = await page.evaluate(() => {

    var $ = window.$

    var items = $('.rank-item')
    var links = []

    if (items.length >= 1) {
      items.each((index, item) => {
        let it = $(item)
        let detail = it.find('.detail')

        let videoNum = Number(it.find('.num').text())
        let videoTitle = it.find('.title').text()
        let videoViews = detail.find('.play').text()
        let videoComments = detail.find('.dm').text()
        let videoAuthor = detail.find('.author').text()

        let videoLink = 'https://www.bilibili.com' + it.find('.content a').attr('href')
        let videoImg = 'https:' + it.find('img').attr('src').replace('@.webp', '')

        links.push({
          videoNum,
          videoTitle,
          videoViews,
          videoComments,
          videoAuthor,
          videoLink,
          videoImg
        })

      })
    }

    return links
  })

  brower.close()

  console.log(result)
})()


function autoScroll(page) {
  return page.evaluate(() => {
    return new Promise((resolve, reject) => {
      var totalHeight = 0
      var distance = 100
      var timer = setInterval(() => {
        var scrollHeight = document.body.scrollHeight
        window.scrollBy(0, distance)
        totalHeight += distance

        if (totalHeight >= scrollHeight) {
          clearInterval(timer)
          resolve()
        }
      }, 100)
    })
  })
}